namespace Ultimate.League.Controls
{
	using System;
	using System.Data;
	using System.Drawing;
	using System.Web;
	using System.Web.UI.WebControls;
	using System.Web.UI.HtmlControls;

	using Ultimate.DAL.CollectionClasses;
	using Ultimate.DAL;
	using Ultimate.DAL.HelperClasses;
	using Ultimate.DAL.EntityClasses;
	using Ultimate.DAL.FactoryClasses;
	using SD.LLBLGen.Pro.ORMSupportClasses;

    using CommunityServer.Components;
	/// <summary>
	///		
	/// </summary>
	public  class SetupGames : System.Web.UI.UserControl
	{
		protected System.Web.UI.WebControls.DataGrid dgLeagues;
		protected System.Web.UI.WebControls.Panel ChooseLeague;
		protected System.Web.UI.WebControls.Panel JoinLeaguePanel;
		protected System.Web.UI.WebControls.Literal Info;
		
		protected System.Web.UI.HtmlControls.HtmlInputRadioButton NewTeam;
		protected System.Web.UI.WebControls.Literal ErrorMessage;
		protected System.Web.UI.WebControls.DropDownList TeamName;
		protected System.Web.UI.WebControls.TextBox NewTeamName;
		protected System.Web.UI.HtmlControls.HtmlInputRadioButton Individual;
		protected System.Web.UI.WebControls.Literal LeagueName;
		protected System.Web.UI.WebControls.TextBox FriendsList;
		protected System.Web.UI.HtmlControls.HtmlInputRadioButton Team;
        protected System.Web.UI.WebControls.DropDownList GameDay;
        protected System.Web.UI.WebControls.DropDownList FieldID;
        protected System.Web.UI.WebControls.DataGrid Games;
        protected System.Web.UI.WebControls.DropDownList HomeTeamID;
        protected System.Web.UI.WebControls.DropDownList AwayTeamID;
        protected System.Web.UI.WebControls.TextBox GameTime;
        protected System.Web.UI.WebControls.TextBox Grouping;


		public int LeagueID
		{
			get
			{
				return Convert.ToInt32(ViewState["LeagueID"]);
			}
			set
			{
				ViewState["LeagueID"] = value;
			}
		}
		/// <summary>
		/// On page load the leagueID is determined and BindData is called.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		protected void Page_Load(object sender, System.EventArgs e)
		{
			if (!this.IsPostBack )
			{
				LeagueID=-1;
				if (Request.QueryString["LeagueID"] != null )
				{
					this.LeagueID = Convert.ToInt32(Request.QueryString["LeagueID"]);
				}
				LeagueEntity le = new LeagueEntity(LeagueID);
                if (!CSContext.Current.User.IsInRoles(new string[] { le.RoleName }))
                {
                    Response.Redirect("~", true);
                }

				DateTime dt = le.StartDate;
				ListItem li;
				int i=0;
				while(dt <= le.EndDate)
				{
					li = new ListItem(dt.ToShortDateString(),i.ToString());
					GameDay.Items.Add(li);
					dt = dt.AddDays(7);
					i++;
				}
				
				
				BindData();
			}
		}
		/// <summary>
	
		/// </summary>
		private void BindData()
		{
			LeagueEntity le = new LeagueEntity(LeagueID);
			DateTime gameDay = le.StartDate.AddDays(7*Convert.ToInt32(GameDay.SelectedValue));
			//Get Teams
			TeamCollection tc = new TeamCollection();
			PredicateExpression A = new PredicateExpression();
			A.Add(PredicateFactory.CompareValue(TeamFieldIndex.LeagueID, ComparisonOperator.Equal, this.LeagueID));
			A.AddWithAnd(new FieldCompareSetPredicate(
				EntityFieldFactory.Create(TeamFieldIndex.TeamID),
				EntityFieldFactory.Create(GameFieldIndex.AwayTeamID),
				SetOperator.NotEqualAll,
				PredicateFactory.CompareValue(GameFieldIndex.GameDay ,	ComparisonOperator.Equal, gameDay)));
			A.AddWithAnd(new FieldCompareSetPredicate(
				EntityFieldFactory.Create(TeamFieldIndex.TeamID),
				EntityFieldFactory.Create(GameFieldIndex.HomeTeamID),
				SetOperator.NotEqualAll,
				PredicateFactory.CompareValue(GameFieldIndex.GameDay ,	ComparisonOperator.Equal, gameDay)));
			ISortExpression sorter = new SortExpression(SortClauseFactory.Create(TeamFieldIndex.TeamName,SortOperator.Ascending));
			tc.GetMulti(A);
			AwayTeamID.DataSource=tc.Items;
			AwayTeamID.DataTextField="TeamName";
			AwayTeamID.DataValueField="TeamID";
			AwayTeamID.DataBind();
			HomeTeamID.DataSource=tc.Items;
			HomeTeamID.DataTextField="TeamName";
			HomeTeamID.DataValueField="TeamID";
			HomeTeamID.DataBind();
			
			//Get Fields
			DAL.TypedListClasses.FieldLocationTypedList fields = new DAL.TypedListClasses.FieldLocationTypedList();
			A = new PredicateExpression();
			A.AddWithAnd(new FieldCompareSetPredicate(
				EntityFieldFactory.Create(FieldFieldIndex.FieldID),
				EntityFieldFactory.Create(GameFieldIndex.FieldID ),
				SetOperator.NotEqualAll,
				PredicateFactory.CompareValue(GameFieldIndex.GameDay ,	ComparisonOperator.Equal, gameDay)));
			 sorter = new SortExpression(SortClauseFactory.Create(LocationFieldIndex.Name,SortOperator.Ascending));
			fields.Fill(0,sorter,false,A);
			FieldID.DataSource=fields.Rows;
			FieldID.DataTextField="FieldName";
			FieldID.DataValueField="FieldID";
			FieldID.DataBind();

			//Bind Games List
			Games.DataSource=DAL.StoredProcedureCallerClasses.RetrievalProcedures.GetGames(gameDay);
			Games.DataBind();

		}
        protected void DayChange(object o, System.EventArgs e)
        {
            BindData();
        }
		protected void AddGame(object o,System.EventArgs e)
		{
			if (Page.IsValid)
			{
				LeagueEntity le = new LeagueEntity(LeagueID);
				GameEntity game = new GameEntity();
				game.HomeTeamID=Convert.ToInt32(HomeTeamID.SelectedValue);
				game.AwayTeamID=Convert.ToInt32(AwayTeamID.SelectedValue);
				game.GameDay=le.StartDate.AddDays(7*Convert.ToInt32(GameDay.SelectedValue));
				game.GameTime=GameTime.Text;
				game.FieldID=Convert.ToInt32(FieldID.SelectedValue);
                game.LeagueID=le.LeagueID;
                game.Grouping=Grouping.Text;
				game.Save();
				BindData();
			}	
		}
		protected void DeleteGame(System.Object o, DataGridCommandEventArgs e)
		{
			int gameID = Convert.ToInt32(Games.DataKeys[e.Item.DataSetIndex]);
			GameEntity game = new GameEntity(gameID);
			game.Delete();
			BindData();
		}

		protected void EditGame(System.Object o, DataGridCommandEventArgs e)
		{
			
			Games.EditItemIndex=e.Item.ItemIndex;
			BindData();
		}
		protected void CancelEditGame(System.Object o, DataGridCommandEventArgs e)
		{
			
			Games.EditItemIndex=-1;
			BindData();
		}
		protected void SaveGame(System.Object o, DataGridCommandEventArgs e)
		{
			int gameID = Convert.ToInt32(Games.DataKeys[e.Item.DataSetIndex]);
			GameEntity game = new GameEntity(gameID);

			game.FieldID=Int32.Parse(((DropDownList) e.Item.FindControl("ddlFields")).SelectedValue);
			game.GameTime=((TextBox) e.Item.FindControl("dgGameTime")).Text;
            game.Grouping = ((TextBox)e.Item.FindControl("txtGrouping")).Text;
			game.HomeHomeScore=Int32.Parse(((DropDownList) e.Item.FindControl("HomeHomeScore")).SelectedValue);
			game.AwayHomeScore=Int32.Parse(((DropDownList) e.Item.FindControl("AwayHomeScore")).SelectedValue);
			game.HomeAwayScore=Int32.Parse(((DropDownList) e.Item.FindControl("HomeAwayScore")).SelectedValue);
			game.AwayAwayScore=Int32.Parse(((DropDownList) e.Item.FindControl("AwayAwayScore")).SelectedValue);
			try
			{
				game.HomeSpiritScore=Double.Parse(((TextBox) e.Item.FindControl("HomeSpiritScore")).Text);
			}
				//TODO:Add Proper error handling code
			catch
			{
				game.SetNewFieldValue("HomeSpiritScore",null);
			}
			try
			{
				game.AwaySpiritScore=Double.Parse(((TextBox) e.Item.FindControl("AwaySpiritScore")).Text);
			}
				//TODO:Add Proper error handling code
			catch
			{
				game.SetNewFieldValue("AwaySpiritScore",null);
			}
			game.Save();
			Games.EditItemIndex=-1;
			BindData();
		}
		protected DAL.TypedListClasses.FieldLocationTypedList GetFields()
		{
			LeagueEntity le = new LeagueEntity(LeagueID);
			DateTime gameDay = le.StartDate.AddDays(7*Convert.ToInt32(GameDay.SelectedValue));
			DAL.TypedListClasses.FieldLocationTypedList fields = new DAL.TypedListClasses.FieldLocationTypedList();
			PredicateExpression A = new PredicateExpression();
			A.AddWithAnd(new FieldCompareSetPredicate(
				EntityFieldFactory.Create(FieldFieldIndex.FieldID),
				EntityFieldFactory.Create(GameFieldIndex.FieldID ),
				SetOperator.NotEqualAll,
				PredicateFactory.CompareValue(GameFieldIndex.GameDay ,	ComparisonOperator.Equal, gameDay)));
			ISortExpression sorter = new SortExpression(SortClauseFactory.Create(LocationFieldIndex.Name,SortOperator.Ascending));
			fields.Fill(0,sorter,false,A);
			return fields;
		}
		protected void Games_ItemDataBound(object sender,	System.Web.UI.WebControls.DataGridItemEventArgs e)
		{
			if(e.Item.ItemType == ListItemType.EditItem)
			{
				//Fields
				DataRowView drv = (DataRowView) e.Item.DataItem;
				String currentField = drv["FieldId"].ToString();
				DropDownList ddl = 	(DropDownList) e.Item.FindControl("ddlFields");
				ddl.SelectedIndex =	ddl.Items.IndexOf(ddl.Items.FindByText(currentField));
				//HomeHomeScore
				String HomeHomeScore = drv["HomeHomeScore"].ToString();
				ddl = 	(DropDownList) e.Item.FindControl("HomeHomeScore");
				ddl.SelectedIndex =	ddl.Items.IndexOf(ddl.Items.FindByText(HomeHomeScore));
				//AwayHomeScore
				String AwayHomeScore = drv["AwayHomeScore"].ToString();
				ddl = 	(DropDownList) e.Item.FindControl("AwayHomeScore");
				ddl.SelectedIndex =	ddl.Items.IndexOf(ddl.Items.FindByText(AwayHomeScore));
				//HomeAwayScore
				String HomeAwayScore = drv["HomeAwayScore"].ToString();
				ddl = 	(DropDownList) e.Item.FindControl("HomeAwayScore");
				ddl.SelectedIndex =	ddl.Items.IndexOf(ddl.Items.FindByText(HomeAwayScore));
				//AwayAwayScore
				String AwayAwayScore = drv["AwayAwayScore"].ToString();
				ddl = 	(DropDownList) e.Item.FindControl("AwayAwayScore");
				ddl.SelectedIndex =	ddl.Items.IndexOf(ddl.Items.FindByText(AwayAwayScore));
			}
		}
		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{

		}
		#endregion
	}
}
